package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    private final StringHttpMessageConverter stringHttpMessageConverter;

    public GlobalExceptionHandler(StringHttpMessageConverter stringHttpMessageConverter) {
        this.stringHttpMessageConverter = stringHttpMessageConverter;
    }

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
    /**
     * 处理SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            try {
                // 定位第一个单引号
                int startIndex = message.indexOf("'") + 1;
                if (startIndex > 0) {
                    // 定位第二个单引号
                    int endIndex = message.indexOf("'", startIndex);
                    if (endIndex > startIndex) {
                        // 提取两个单引号之间的内容（用户名）
                        String username = message.substring(startIndex, endIndex);
                        String msg = username + MessageConstant.ACCOUNT_EXISTS;
                        return Result.error(msg);
                    }
                }
            } catch (Exception e) {
                // 处理异常情况，避免程序崩溃
                log.error("提取用户名失败", e);
            }
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }
}
